package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	//"time"
)

import "runtime"
import "sync"

import "sort"

import "strconv"

// // 导入依赖包
// import "test"

// // NAME 常量定义
// const NAME string = "zbw"

// // a 全局变量定义
// var a string = "zbw"

// // Learn 声明结构体
// type Learn struct {
// }

// // Ilearn声明接口
// type Ilearn interface {
// }

// // 声明函数
// func learnZbw() {
// 	fmt.Print("learn zbw")
// }
// 基础学习
func study() {
	var s1 []int
	s2 := make([]int, 10, 10)                    //中括号中如果是数组或者...的话才是数组，空的话是slice
	a1 := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} //此处为数组
	fmt.Println(a1[:5])
	fmt.Println(s2)
	fmt.Println(s1)
	if a := 65; a > 0 {
		fmt.Println("当前数据数：" + strconv.Itoa(a))
	}
	//map 中数据是无序的
	m := map[int]string{1: "zbw", 2: "wkk", 3: "zwx"}
	s := make([]int, len(m))
	i := 0
	for k, _ := range m {
		s[i] = k
		i++
	}
	sort.Ints(s)
	fmt.Print(s)
}

//协程演示
func goroutine() {
	arr := map[string]string{
		"name": "pingye",
		"sex":  "1",
		"age":  "30",
	}
	for k := range arr {
		fmt.Println(k)
	}

	fmt.Println("name的值为：" + arr["name"])
	fmt.Println(runtime.NumCPU())
	runtime.GOMAXPROCS(runtime.NumCPU())
	// c := make(chan bool, 10)
	wg := sync.WaitGroup{}
	wg.Add(10)
	for i := 0; i < 10; i++ {
		go Go(&wg, i)
	}
	wg.Wait()
}

// 获取url中数据
func geturl() {
	r, err := http.Get("http://httpbin.org/anything?hello=world")
	if err != nil {
		panic(err)
	}
	defer r.Body.Close()

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("body = %s\n", string(body))
}
func Go(wg *sync.WaitGroup, index int) {
	a := 1
	for i := 0; i < 10000000; i++ {
		a += i
	}
	fmt.Println(index, a)

	wg.Done()
}

// 不定长变参数 只能是最后一个如果传递的slice则是地址的拷贝会影响原变量值
// go中函数也是类型也可以赋值
func A(a ...int) {
	fmt.Print(a)
}

type worker struct {
	in chan int
	wg *sync.WaitGroup
}

func dowork(id int, c chan int, wg *sync.WaitGroup) {
	for n := range c {
		fmt.Printf("worker %d received %c\n", id, n)
		wg.Done()
	}
}
func createWorker(id int, wg *sync.WaitGroup) worker {
	w := worker{
		in: make(chan int),
		wg: wg,
	}
	go dowork(id, w.in, wg)
	return w

}

// channel 示例
func chanDemo() {
	var wg sync.WaitGroup

	var workers [10]worker
	for i := 0; i < 10; i++ {
		workers[i] = createWorker(i, &wg)
	}
	wg.Add(20)
	for i, worker := range workers {
		worker.in <- 'a' + i
	}
	for i, worker := range workers {
		worker.in <- 'A' + i

	}
	wg.Wait()
}

// 主函数
func main1() {
	chanDemo()
	// for i := 0; i < 10; i++ {
	// 	go func(i int) {
	// 		for {
	// 			//runtime.Gosched() // 手动切换控制权
	// 			fmt.Printf("hello from"+"goroutine %d\n", i)
	// 		}
	// 	}(i)
	// }
	// time.Sleep(time.Minute)
	//test.Hello()
	// A(1, 2, 3)

}
